package com.sxhalo.fsms.controller.api;

import com.sxhalo.fsms.controller.BaseController;
import com.sxhalo.fsms.domain.*;
import com.sxhalo.fsms.export.ExcelUtils;
import com.sxhalo.fsms.export.ExportSetInfo;
import com.sxhalo.fsms.log.SysControllerLog;
import com.sxhalo.fsms.quartz.AlarmEnum;
import com.sxhalo.fsms.service.IDeviceAlarmRecordService;
import com.sxhalo.fsms.service.IFactDeviceAlarmRuleService;
import com.sxhalo.fsms.service.ISysDeviceAttrService;
import com.sxhalo.fsms.service.IUserInfoService;
import com.sxhalo.fsms.socket.WebSocketServer;
import com.sxhalo.fsms.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/api")
public class DeviceAlarmController extends BaseController {

	@Autowired
	private IDeviceAlarmRecordService iAlarmRecordService;
	@Autowired
	private IFactDeviceAlarmRuleService iAlarmRuleService;
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private ISysDeviceAttrService attrService;

	@ResponseBody
	@RequestMapping(value = "/deviceAlarmRecord", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findAlarmRecord(Integer deviceId,Integer ruleId,Integer current, Integer pageSize, HttpServletRequest req) {
		String where = "id is not NULL";
		String order = " state,alarm_time desc,alarm_level,alarm_type";

		String selAlarmType[] = req.getParameterValues("selAlarmType");
		String selHandleType[] = req.getParameterValues("selHandleType");
		String serText = req.getParameter("serText");
		String selFactArea = req.getParameter("selFactArea");
		String seldeviceType = req.getParameter("seldeviceType");
		String selRangePicker[] = req.getParameterValues("selRangePicker");

		if (selAlarmType != null&&!selAlarmType[0].equals("")) {
			where += " and (alarm_level = '" + selAlarmType[0]+"'";
			for (int i = 1; i < selAlarmType.length; i++) {
				where += " or alarm_level = '" + selAlarmType[i]+"'";
			}
			where+=") ";
		}
		if ((selHandleType != null) && (selHandleType.length == 1)) {
			where += " and state = " + selHandleType[0];
		}
		if (!isBlank(serText)) {
			where += " and alarm_value like '%" + serText.trim() + "%'";
		}
		if (!isBlank(selFactArea)) {
			where += " and area_id = " + selFactArea;
		}
		if (!isBlank(seldeviceType)) {
			where += " and device_type_id = " + seldeviceType;
		}
		if (selRangePicker != null) {
			where += " and alarm_time between '" + selRangePicker[0] + "' and '" + selRangePicker[1] + "'";
		}
		if (deviceId != null) {
			where += " and device_id=" + deviceId;
		}

		if (ruleId != null) {
			where += " and rule_id   =" + ruleId;
		}
		Integer count = iAlarmRecordService.getSearchCount(where);
		List<DeviceAlarmRecord> list = iAlarmRecordService.findPagerList((current - 1) * pageSize, pageSize, where,	order);
		PageData page = new PageData(current, pageSize, count, list);
		return ApiResult.retOK(req, page);
	}


	@ResponseBody
	@RequestMapping(value = "/queryDeviceAlarmNotices", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult queryDeviceAlarmNotices(Integer size,  HttpServletRequest req) {

		List<DeviceAlarmRecord> alarmRecord=iAlarmRecordService.findWhereList("state=0","create_time desc,alarm_level desc,alarm_type asc");

		return ApiResult.retOK(req, alarmRecord);
	}


	@ResponseBody
	@RequestMapping(value = "/alarm/rules", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findAlarmRuleList(Integer deviceId,Integer current, Integer pageSize, HttpServletRequest req) {
		String where = "a1.delete_flag = 0";
		String order = " a1.update_time desc";

		if(!isBlank(req.getParameter("alarmName"))) {
			where += " and alarm_name like '%" + req.getParameter("alarmName").trim() + "%'";
		}

		if(!isBlank(req.getParameter("alarmType"))) {
			where += " and alarm_type = '" + req.getParameter("alarmType")+ "'";
		}

		if(!isBlank(req.getParameter("alarmLevel"))) {
			where += " and alarm_level = '" + req.getParameter("alarmLevel")+ "'";
		}

		if(!isBlank(req.getParameter("deviceName"))) {
			where += " and device_name like '%" + req.getParameter("deviceName").trim()+"%'";
		}

		if(deviceId!=null){
			where += " and device_id = "+deviceId;
		}

		return findList(current, pageSize, where, order, iAlarmRuleService);
	}


	@ResponseBody
	@SysControllerLog(operationName = "批量更新启用状态", modelName = "报警规则")
	@RequestMapping(value = "/alarm/rules/batchUpdate", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ApiResult saveDevice(FactDeviceAlarmRule record, String ids, HttpServletRequest req) {
		record.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		iAlarmRuleService.batchUpdate(record, " id in (" + ids + ")");

		return ApiResult.retOK(req);
	}

	@ResponseBody
	@RequestMapping(value = "/alarm/rules/attr", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findAlarmRuleListByAttr(Integer deviceId,Integer attrId, HttpServletRequest req) {
		String where = "delete_flag = 0";
		String order = " alarm_type";
		if(deviceId!=null){
			where += " and device_id = "+deviceId;
		}
		if(attrId!=null){
			where += " and attr_id = "+attrId;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		SysDeviceAttr attr=attrService.selectByPrimaryKey(attrId);
		List<FactDeviceAlarmRule> list = iAlarmRuleService.findWhereList(where, order);
		for(FactDeviceAlarmRule rule:list){
			if(rule.getAlarmType().equals("602")){
				map.put("useState1",rule.getUseState()==1? true:false);
				map.put("number1",rule.getMaxValue());
			}else if(rule.getAlarmType().equals("603")){
				map.put("useState2",rule.getUseState()==1? true:false);
				map.put("number1",rule.getMaxValue());
				map.put("number2",rule.getMinValue());
			}else if(rule.getAlarmType().equals("604")){
				map.put("useState3",rule.getUseState()==1? true:false);
				map.put("number3",rule.getMaxValue());
				map.put("number4",rule.getMinValue());
			}else if(rule.getAlarmType().equals("605")){
				map.put("useState4",rule.getUseState()==1? true:false);
				map.put("number4",rule.getMinValue());
			}



		}
		map.put("attr",attr);

		return ApiResult.retOK(req,map);
	}

	@ResponseBody
	@SysControllerLog(operationName = "新增报警规则", modelName = "报警规则")
	@RequestMapping(value = "/alarm/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ApiResult saveAlarmRule(FactDeviceAlarmRule record,String[] ids, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setId(iAlarmRuleService.getMaxId()+1);
		record.setUpdateTime(nowtime);
		record.setDeleteFlag(0);
		record.setCreateTime(nowtime);
		iAlarmRuleService.batchInsert(record,ids);

		CacheUtil.removeObject("rules");
		return ApiResult.retOK(req);
	}
	
	
	@ResponseBody
	@SysControllerLog(operationName = "更新报警规则", modelName = "报警规则")
	@RequestMapping(value = "/alarm/update", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult updateAlarmRule(@RequestBody FactDeviceAlarmRule record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		iAlarmRuleService.updateByPrimaryKeySelective(record);

		CacheUtil.removeObject("rules");
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "更新报警规则", modelName = "报警规则")
	@RequestMapping(value = "/alarm/updateOrsave", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult updateOrSaveAlarmRule(@RequestBody FactDeviceAlarmRule record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		FactDeviceAlarmRule rule= iAlarmRuleService.findWhere("delete_flag=0 and device_id="+record.getDeviceId()+" and attr_id="+record.getAttrId()+" and alarm_type=" +record.getAlarmType(),null);
		 if(rule==null&&record.getUseState()==1){
			 record.setCreateTime(nowtime);
			 record.setUpdateTime(nowtime);
			 record.setDeleteFlag(0);
			 iAlarmRuleService.insertSelective(record);
		 }else if(rule!=null){
			 record.setId(rule.getId());
			 record.setUpdateTime(nowtime);
			 iAlarmRuleService.updateByPrimaryKeySelective(record);
		 }

		CacheUtil.removeObject("rules");
		return ApiResult.retOK(req);
	}



	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "报警规则")
	@RequestMapping(value = "/alarm/rules/batchdel", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult batchDelRules(String  ids, String method, HttpServletRequest req) {
		FactDeviceAlarmRule record=new FactDeviceAlarmRule();
		record.setDeleteFlag(1);
		record.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		iAlarmRuleService.batchUpdate(record, " id in (" + ids + ")");

		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "删除报警规则", modelName = "报警规则")
	@RequestMapping(value = "/alarm/del", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult delAlarmRule(@RequestBody FactDeviceAlarmRule record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		record.setDeleteFlag(1);
		iAlarmRuleService.updateByPrimaryKeySelective(record);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "删除", modelName = "报警记录")
	@RequestMapping(value = "/alarm/record", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult delAlarmRecord(Integer id, HttpServletRequest req) {
		iAlarmRecordService.deleteByPrimaryKey(id);
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "报警记录")
	@RequestMapping(value = "/alarm/record/batchdel", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public ApiResult batchDelAlarmRecord(String ids, HttpServletRequest req) {
		iAlarmRecordService.deleteByWhere(" id in ("+ids+")");
		return ApiResult.retOK(req);
	}

	/**首页报警记录统计*/
	@ResponseBody
	@RequestMapping(value = "/queryDeviceCount", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ApiResult queryDeviceCount(HttpServletRequest req) {
		Integer highCount = iAlarmRecordService.getCount(" alarm_type = 601");
		Integer centreCount = iAlarmRecordService.getCount(" alarm_type = 602");
		Integer downCount = iAlarmRecordService.getCount(" alarm_type = 603");
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("highCount", highCount);
		map.put("centreCount", centreCount);
		map.put("downCount", downCount);
		return ApiResult.retOK(req, map);
	}
	
	@ResponseBody
	@SysControllerLog(operationName = "处置报警方记录", modelName = "报警记录")
	@RequestMapping(value = "/alarm/handle", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult alarmHandle(@RequestBody DeviceAlarmRecord record, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());		
		Integer userId = null;
		String token = CookieUtils.getCookieValue(req, "token");
		if (token != null) {
			userId = TokenUtil.getUserId(token);
		}
		UserInfo user = userInfoService.selectByPrimaryKey(userId);
		if(user!=null) {
			record.setUserId(user.getUserId());
			record.setUserName(user.getUserName());
		}
		record.setState(1);
		record.setHandleTime(nowtime);
		record.setUpdateTime(nowtime);
		iAlarmRecordService.updateByPrimaryKeySelective(record);



		sendSocket();
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "批量处置报警方记录", modelName = "报警记录")
	@RequestMapping(value = "/alarm/batchHandle", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	public ApiResult alarmBatchHandle( DeviceAlarmRecord record,String ids, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		Integer userId = null;
		String token = CookieUtils.getCookieValue(req, "token");
		if (token != null) {
			userId = TokenUtil.getUserId(token);
		}
		UserInfo user = userInfoService.selectByPrimaryKey(userId);
		if(user!=null) {
			record.setUserId(user.getUserId());
			record.setUserName(user.getUserName());
		}
		record.setState(1);
		record.setHandleTime(nowtime);
		record.setUpdateTime(nowtime);
		iAlarmRecordService.batchUpdateByWhere(record," id in (" + ids + ") and state=0");

		sendSocket();


		return ApiResult.retOK(req);
	}

	//发送最新报警信息
	private void sendSocket(){
		List<DeviceAlarmRecord> alarmRecord=iAlarmRecordService.findWhereList("state=0","create_time desc,alarm_level desc,alarm_type asc");
		Map<String, Object> msgData = new HashMap<String, Object>();
		msgData.put("AlarmData",alarmRecord);
		//报警数据发送
		WebSocketServer.sendMessage(msgData);
	}

	//表头选择
	private List<String[]> createUsersExcelHead() {
		List<String[]> headlist = new ArrayList<String[]>();
		String[] row1 = { "ID","报警时间","报警设备", "报警变量","报警级别","报警数值","信息来源","处置状态","报警处置信息","处置人","处置时间"};
		headlist.add(row1);
		return headlist;
	}
	
	
	@SysControllerLog(operationName = "导出", modelName = "报警记录")
	@RequestMapping(value = "/exportAlarmRecordExcel", method = RequestMethod.GET)
	public void deviceDownload(String keyword, HttpServletRequest req, HttpServletResponse response) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		String fileName = "报警记录";
		String[] Userkeys = { "id", "alarmTime", "deviceName", "browseName", "alarmLevel",  "alarmValue", "defectSource",
				"state", "alarmHandle", "userName", "handleTime" };

		String where = "";
		String order = "";
		List<DeviceAlarmRecord> data = iAlarmRecordService.findPagerList(0, -1, where, order);
		ExportSetInfo info = new ExportSetInfo();
		List<Map<String, Object>> record = createUserListRecord(data);
		info.setHeadNames(createUsersExcelHead());
		info.setDatalist(record);
		info.setTitles(fileName);
		info.setFieldNames(Userkeys);
		info.setOut(os);
		ExcelUtils.export2Excel(info);
		ExcelUtils.ExcelDownload(fileName, response, os);

	}
	
	private List<Map<String, Object>> createUserListRecord(List<DeviceAlarmRecord> data) {	
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		for (DeviceAlarmRecord fd: data) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", fd.getId());
			mapValue.put("alarmTime",  DateUtil.sdf.format(fd.getAlarmTime()));
			mapValue.put("deviceName", fd.getDeviceName());
			mapValue.put("browseName", fd.getBrowseName());
//			mapValue.put("alarmType", AlarmEnum.getCategoryMsg(fd.getAlarmType()));
			mapValue.put("alarmLevel", AlarmEnum.getLevelMsg(fd.getAlarmLevel()));
			mapValue.put("alarmValue", fd.getAlarmValue());
			mapValue.put("defectSource", AlarmEnum.getSourceMsg(fd.getAlarmLevel()));
			mapValue.put("state", fd.getState()==0?"未处置":"已处置");
			mapValue.put("alarmHandle", fd.getAlarmHandle());
			mapValue.put("userName", fd.getUserName());
			mapValue.put("handleTime", fd.getHandleTime()==null?"":DateUtil.sdf.format(fd.getHandleTime()));
			
			listmap.add(mapValue);
		}
		return listmap;
	}




}
